import { AccountApi } from '@/api/userCenter/authority/account'
import { MenuItem } from '@/api/userCenter/system/model/menuModel'
import { useStore } from '@/store'
import { LoginFormParams } from '@/store/account/actions'
import { message } from 'ant-design-vue'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const useLogin = () => {
  const router = useRouter()
  const store = useStore()
  const isOne = ref(true)
  const isSec = ref(false)
  const formData = ref<LoginFormParams>({ username: '', password: '' })
  const permList = ref<MenuItem[]>([])

  const login = async () => {
    await store.dispatch('account/LOGIN', formData.value)
    permList.value = store.state.account.currentUser?.perms || []
    if (permList.value.length === 1) {
      store.commit('account/SAVE_MENU_LIST', permList.value[0].id)
      router.push('/welcome')
      message.success('登陆成功')
    } else {
      message.success('登陆成功', 1, () => message.info('请选择系统进入'))
      isOne.value = false
    }
  }
  const loginLoading = computed(() =>
    store.getters['global/isOpLoading'](AccountApi.LOGIN)
  )

  const backLogin = () => {
    store.commit('account/DELETE_ACCOUNT_INFO')
    store.commit('account/DELETE_MENU_LIST')
    isSec.value = false
  }

  return {
    formData,
    login,
    loginLoading,
    isSec,
    isOne,
    backLogin,
    permList,
  }
}

export default useLogin
